package com.jn.okhttp.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.jn.okhttp.common.WeakRrfHandler;
import com.jn.okhttp.contract.DictionaryContact;
import com.jn.okhttp.entity.Dictionary;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DictionaryPresenter implements DictionaryContact.DictionaryPresenter {
    private static final int HTTP_SUCCESS = 1 ;
    private static final int HTTP_FAIL = 0 ;
    private DictionaryContact.DictionaryView mMainView ;
    private Context mContext ;
    private OkHttpClient mClient ;

    public DictionaryPresenter(DictionaryContact.DictionaryView mMainView , Context mContext){
        this.mMainView = mMainView ;
        this.mContext = mContext ;
        mClient = new OkHttpClient() ;
    }

    @Override
    public void getData(String keyWord) {
        Request request = new Request.Builder()
                .url("https://api.oioweb.cn/api/txt/dict?text=" + keyWord)
                .build() ;
        Call call = mClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String body = response.body().string() ;
                String url = call.request().url().toString() ;
                Message message = Message.obtain() ;
                message.obj = new String[]{body , url} ;
                message.what = HTTP_SUCCESS ;
                mHandler.sendMessage(message);
            }
        });
    }

    WeakRrfHandler<DictionaryPresenter> mHandler = new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int result = msg.what;
            switch (result) {
                case HTTP_SUCCESS:
                    String[] data = (String[]) msg.obj;
                    if (data == null || data.length < 2) {
                        return false;
                    }
                    String jsonStr = data[0];
                    Gson gson = new Gson();
                    Dictionary dictionariesEntity = gson.fromJson(jsonStr, Dictionary.class);
                    if (mMainView != null) {
                        mMainView.showData(dictionariesEntity);
                    }
                    break;
                case HTTP_FAIL:
                    break;
            }
            return false;
        }
    });
}
